我有一个算法可以根据简单的移动平均值来购买股票,但是我一直在试图给动态列表分配一个百分比。在
例如,该算法允许在第一周购买四只股票,因此创建一个包含四个元素的列表:["apple", "google", "tesla", "AMD"]
。在
接下来的一周,它购买了六只股票,并创建了一份包含六只股票的清单:["apple", "google", "tesla", "AMD", "intel", "qualcomm"]
。在
我要做的是动态地为列表中的每个元素分配一个百分数,这个百分比等于100%。在
因此,在第一周,苹果将被分配50%,谷歌占25%,特斯拉占15%,AMD占10%。在
在第二周,苹果可能被分配50%,谷歌占25%,特斯拉16.5%,AMD 5%,英特尔2.5%,高通1%。在
在最后的结果中,我希望给算法一个数字列表,并为每个元素分配一个百分比,从高到低,但仍然等于100%。在
我现在的代码是:
from quantopian.pipeline.factors import VWAP
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q1500US
import numpy as np
import pandas as pd
import math
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Sets default slippage and commission fees to simulate real trading.
set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
set_asset_restrictions(security_lists.restrict_leveraged_etfs)
# Creates a function that runs at the beginning of each week.
schedule_function(start_of_week, date_rules.week_start(), time_rules.market_open(hours=1))
# Rebalance every day, 1 hour after market open.
schedule_function(my_rebalance, date_rules.week_end(), time_rules.market_open(hours=1))
# Record tracking variables at the end of each day.
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
#Creates a function that runs at the beginning of everyday.
schedule_function(start_of_day, date_rules.every_day(), time_rules.market_open(hours=1.5))
# Create our dynamic stock selector.
pipe = Pipeline()
attach_pipeline(pipe, name='my_pipeline')
# Construct Volume Factor.
vwap = VWAP(inputs=[USEquityPricing.close, USEquityPricing.volume], window_length=14)
prices_under_5 = (vwap < 5)
pipe.set_screen(prices_under_5)
context.df_long = pd.DataFrame(None, columns=list("ABC"))
context.df_short = pd.DataFrame(None, columns=list("ABC"))
context.long_list = []
context.short_list = []
def start_of_week(context, data):
"""
Called at the begining of every week before market open.
"""
context.df_long = pd.DataFrame(None, columns=list("AB"))
context.df_short = pd.DataFrame(None, columns=list("AB"))
context.long_list = []
context.short_list = []
context.output = pipeline_output('my_pipeline')
# These are the securities that we are interested in trading each day.
context.security_list = context.output.sort_index(axis=0, ascending=True, kind='quicksort')
context.security_list = context.security_list.index
for security in context.security_list:
# Gets Simple Moving Average for 7 days and 100 days
price_hist_8 = data.history(security, 'price', 7, '1d')
mavg8 = price_hist_8.mean()
price_hist_14 = data.history(security, 'price', 100, '1d')
mavg14 = price_hist_14.mean()
current_vol = data.current(securrity, "volume")
if mavg8 > mavg14:
#Calculate percent increase of volume
current_vol = data.current(security, "volume")
hist_vol = data.history(security, "volume", 10, "1d")
difference_increase_vol = current_vol - hist_vol
percent_increase_vol = (difference_increase_vol / hist_vol) * 100
percent_increase_vol = percent_increase_vol[0]
if perecent_increase_vol >= 0:
context.df_long_tbd = pd.DataFrame([[security, mavg8]], columns=list("AB"))
frames = [context.df_long, context.df_long_tbd]
context.df_long = pd.concat(frames)
# Sorts all of the stocks in the "long" Data Frame from steepest incline in simple moving average over 8 days. The "final_long_list" contains all of the top stocks' names.
result_long = context.df_long.sort_values(by=["B", "A"], ascending=False)
context.long_final_list = result_long["A"]
# Total amout of stocks that the algorithim is allowed to buy will be determined on total portfolial value.
# If the total portfolial value is $100,000, the algorithim is only allowed to look at
port_val = context.portfolio.portfolio_value
allowed_to_purchase = round(sqrt(port_val)/10)
for stock in context.long_final_list[:allowed_to_purchase]:
if data.can_trade(stock):
假设“允许购买”等于10。现在,我想分配我的前十名的每只股票context.long_最终列表一个百分比,从高到低,等于100%。在
是否有简单的解决方案或内置函数?”context.long_最终列表“是熊猫的数据框,熊猫有没有功能?在
解决了!如果我把所有的股票价值加在一个总的单一条款中,然后用总条款除以每只股票的价值。在
例如在我的熊猫数据框中context.long_最终列表公司名称:
相关问题 更多 >
编程相关推荐